<template>
  <div class="pubmap-box">
    <div class="pubmap-content">
      <div class="longitude">
        <label>经度：</label>
        <Input v-model="longtitude" size="large" placeholder="请输入经度"/>
      </div>
      <div class="latitude">
        <label>纬度：</label>
        <Input v-model="latitude" size="large" placeholder="请输入纬度"/>
      </div>

      <div class="magnitude">
        <label>震级：</label>
        <Input v-model="magnitude" size="large" placeholder="请输入震级"/>
      </div>
      <div class="depth">
        <label>深度：</label>
        <Input v-model="depth" size="large" placeholder="请输入深度"/>
      </div>

      <div class="time">
        <label>时间：</label>
        <DatePicker type="datetime" size="large" placeholder="自定义日期格式" v-model="time"></DatePicker>
      </div>

      <div class="btn">
        <Button type="success" class="pub-cho" @click="getGooglePoint()">选择震源</Button>
        <Button type="success" class="pub-cho pub-cho-yes" @click="getCityName()">确认提交</Button>
      </div>
    </div>
    <div id="seismicinfoGmap"></div>
  </div>
</template>

<script>
import circlePng from "@/assets/mapimg/circle.png";
import ajax from "axios";
import qs from "qs";
import pub from "@/assets/pubFile.json";
import date from "@/components/pubcomponent/date.vue";

export default {
  name: "pubmapBox",
  data() {
    return {
      longtitude: null,
      latitude: null,
      depth: null,
      magnitude: null,
      time: null,
      map: null,
      street: null,
      district: null,
      city: null,
      province: null,
      Intensity: null,
      point: null,
      learnmarker: null,
      circlePng: circlePng
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      this.map = new google.maps.Map(
        document.getElementById("seismicinfoGmap"),
        {
          zoom: 10,
          streetViewControl: false,
          center: { lat: 39.915, lng: 116.404 }
        }
      );
    },
    // 将经纬度从谷歌地图偏移到百度地图
    googleToBd(gcjLat, gcjLon) {
      let PI = 3.14159265358979324;
      let x_pi = (3.14159265358979324 * 3000.0) / 180.0;
      let x = gcjLon,
        y = gcjLat;
      let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
      let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
      let bdLon = z * Math.cos(theta) + 0.0065;
      let bdLat = z * Math.sin(theta) + 0.006;
      return { lat: bdLat, lon: bdLon };
    },
    //根据坐标获取地区名称
    getCityName() {
      this.$Message.loading({
        content: "Loading...",
        duration: 0
      });
      // this.longtitude = parseFloat(parseFloat(this.longtitude).toFixed(4)); //经度
      // this.latitude = parseFloat(parseFloat(this.latitude).toFixed(4)); //纬度
      let x = parseFloat(parseFloat(this.longtitude).toFixed(4));
      let y = parseFloat(parseFloat(this.latitude).toFixed(4));
      let coordinate = this.googleToBd(y, x);
      let lon = parseFloat(parseFloat(coordinate.lon).toFixed(4));
      let lat = parseFloat(parseFloat(coordinate.lat).toFixed(4));
      // console.log(coordinate);

      this.depth = parseFloat(this.depth); //深度
      this.magnitude = parseFloat(this.magnitude); //震级
      // this.time; //时间
      this.Intensity = parseInt(this.magnitude) + 2;
      if (
        // !this.longtitude ||
        // !this.latitude ||
        !lon ||
        !lat ||
        !this.depth ||
        !this.magnitude ||
        !this.time ||
        !this.Intensity
      ) {
        //消息弹框
        this.$Message.warning("请完善数据");
      } else {
        this.getCity(lat, lon);
      }
    },
    //获得县名称
    getCity(lat, lon) {
      this.point = new google.maps.LatLng({
        // lat: this.latitude,
        // lng: this.longtitude
        lat: lat,
        lng: lon
      });
      let geocoder = new google.maps.Geocoder(); //定位到经纬度的地方
      this.map.setCenter(this.point);
      this.map.setZoom(10);
      let marker = new google.maps.Marker({
        position: this.point,
        map: this.map,
        icon: this.circlePng
      });
      let that = this;
      geocoder.geocode({ location: that.point }, function(results, status) {
        //此处this指向会发生改变，所以用上面提前指向的that
        //因为函数嵌套，所以this指向了window，that才是指向当前对象
        if (status === "OK") {
          if (results[1]) {
            that.map.setCenter(that.point);
            results[0].address_components[0] != undefined
              ? (that.street = results[0].address_components[0].long_name)
              : (that.street = null);
            results[0].address_components[1] != undefined
              ? (that.district = results[0].address_components[1].long_name)
              : (that.district = null);
            results[0].address_components[2] != undefined
              ? (that.city = results[0].address_components[2].long_name)
              : (that.city = null);
            results[0].address_components[3] != undefined
              ? (that.province = results[0].address_components[3].long_name)
              : (that.province = null);

            ajax({
              method: "post",
              url:
                "http://" + pub.ip + "/subaoApi/public/index/pubear/baseInfo",
              data: qs.stringify({
                longtitude: that.longtitude,
                latitude: that.latitude,
                depth: that.depth,
                magnitude: that.magnitude,
                time: that.time.format("yyyy-MM-dd hh:mm:ss"),
                city: that.city,
                province: that.province,
                district: that.district,
                Intensity: that.Intensity,
                street: that.street
              }),
              //允许携带cookie
              withCredentials: true
            })
              .then(res => {
                that.$Message.destroy();
                that.$Message.success("提交成功");
                let data = eval("(" + res.data + ")");
                if (!isNaN(data)) {
                  data = parseInt(data);
                  if (data) {
                    that.$Message.success("发布成功");
                  } else {
                    that.$Message.error("找不到城市");
                  }
                } else {
                  that.$Message.error("无数据");
                }
              })
              .catch(err => {
                that.$Message.destroy();
                that.$Message.error("网络错误");
                console.error(err);
              });
          } else {
            that.$Message.destroy();
            that.$Message.error("非中国地域");
            that.map.setCenter(that.point);
          }
        } else {
          that.$Message.destroy();
          that.$Message.error("请求失败");
          that.map.setCenter(that.point);
        }
      });
    },
    //获取圆心点
    getGooglePoint() {
      let that = this;
      let click_addmarker = google.maps.event.addListener(
        that.map,
        "click",
        function(event) {
          addmarkerpoint(event);
        }
      );
      function addmarkerpoint(event) {
        if (that.learnmarker != undefined) {
          that.learnmarker.setMap(null);
        }
        if (event.latLng) {
          let marker = new google.maps.Marker({
            position: event.latLng,
            map: that.map,
            icon: that.circlePng
          });
          that.learnmarker = marker;
          let x = marker.getPosition();
          that.longtitude = x.lng().toFixed(4);
          that.latitude = x.lat().toFixed(4);
          google.maps.event.removeListener(click_addmarker);
        }
      }
    }
  },
  components: {
    date
  }
};
</script>

<style>
.pubmap-box {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  border-top: 1px #639c70 solid;
}
.pubmap-content {
  position: relative;
  width: 100%;
  height: 150px;
}
.longitude {
  position: absolute;
  display: inherit;
  top: 20%;
  left: 5%;
}
.latitude {
  position: absolute;
  display: inherit;
  top: 60%;
  left: 5%;
}
.magnitude {
  position: absolute;
  display: inherit;
  top: 20%;
  left: 25%;
}
.depth {
  position: absolute;
  display: inherit;
  top: 60%;
  left: 25%;
}
.time {
  position: absolute;
  display: inherit;
  top: 20%;
  left: 45%;
}
.btn {
  position: absolute;
  top: 40%;
  left: 70%;
}
.pub-cho {
  height: 40px;
  width: 100px;
  padding: 0px 18px;
  text-align: center;
  display: inline-block;
}
.pub-cho-yes {
  position: absolute;
  left: 200px;
}
.pubmap-box .pubmap-content .ivu-input-wrapper {
  width: 80%;
}
#seismicinfoGmap {
  position: absolute;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  border-top: 3px #639c70 solid;
}
</style>
